<?php
class sina_api extends SaeTClientV2{
	private $akey;
	private $skey;	
	private $return_url;
	//private $oauth;
	//private $atoken;
	//private $rtoken;
	
	
	function __construct($type='reg') {
		$api_type = $type;
	    require_once(CONFIG_PATH.'sina_config.php');
	    $this->akey = WB_AKEY;
	    $this->skey = WB_SKEY;
	    $this->return_url = WB_CALLBACK_URL;
	    $this->oauth = new SaeTOAuthV2( $this->akey, $this->skey);
	    
	   // parent::__construct($akey, $skey, $access_token, $refresh_token);//
	}
	
	
	
	public function get_user_info(){	
	    $access_token = $this->get_atoken();		
		if($access_token){		
			$this->oauth = new SaeTOAuthV2($this->akey, $this->skey, $access_token );
			$user_get = $this->get_uid();
			$uid = $user_get['uid'];
			$user_info = $this->show_user_by_id($uid);
			return $user_info;
		}
	}
	
	public function check_login($code){
	    $keys = array();
	    $keys['code'] = $code;
	    $keys['redirect_uri'] = $this->return_url;
	    $token = $this->oauth->getAccessToken( 'code', $keys );
	    if($token){
		$_SESSION['sina_token'] = $token;
		setcookie( 'weibojs_'.$this->oauth->client_id, http_build_query($token['access_token']) );
		
		return true;
	    }else{
		return false;
	    }	
	}
	
	public function logout(){
		$access_token = $this->get_atoken();
	    $this->oauth = new SaeTOAuthV2($this->akey, $this->skey, $access_token );
		$rs=$this->oauth->get('account/end_session');

		setcookie( 'weibojs_'.$this->oauth->client_id, http_build_query($token['access_token']),time()-3600 );
		unset($_SESSION['sina_token']);
		unset($_SESSION['user_auth']);
		header("location:/default/index.htm");
	    //return $this->oauth->get( 'account/end_session' );
	}
	
	public function get_atoken(){
	    if(isset($_SESSION['sina_token']['access_token']))
	    return $_SESSION['sina_token']['access_token'];
	}
	
	public function get_rtoken(){
	    if(isset($_SESSION['sina_token']['refresh_token']))
	    return $_SESSION['sina_token']['refresh_token'];
	}
	
	public function set_return_url($url){
	    if($url){
		$this->return_url = $url;
	    }
	}
	
	public function upload_weibo($content,$img){
		$access_token = $this->get_atoken();
	    if($access_token){
			$this->oauth = new SaeTOAuthV2($this->akey, $this->skey, $access_token );
			$rs = $this->upload($content,$img);
			if(isset($rs['mid'])){
				return $rs['mid'];
				//return true;	
			}else{
				return false;	
				//$rs['error_code']
			}
		}
	}
}


?>